package cmd

import (
	"fmt"
	"github.com/shirou/gopsutil/process"
	"github.com/spf13/cobra"
	"io/ioutil"
	"strconv"
)

func init() {
	stopCmd := &cobra.Command{
		Use:   "stop",
		Short: "停止程序",
		Long:  `读取pid中的进程id,来停止程序`,
		Run: func(cmd *cobra.Command, args []string) {
			strb, _ := ioutil.ReadFile("pid")
			if len(strb) > 0 {
				fmt.Println("pid:", string(strb))
				parseInt, _ := strconv.ParseInt(string(strb), 10, 32)
				pn, _ := process.NewProcess(int32(parseInt))
				pn.Kill()
				// 结束后清空pid
				ioutil.WriteFile("pid", []byte(""), 0666)
				// 该方法在windows下无效
				//command := exec.Command("kill", string(strb))
				//command.Start()
				//println("gonne stop")
			} else {
				fmt.Println("程序未运行!")
			}
		},
	}
	rootCmd.AddCommand(stopCmd)
}
